package com.uinnova.youshuyun.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uinnova.youshuyun.mapper.InstrumentMapper;
import com.uinnova.youshuyun.model.Instrument;
import com.uinnova.youshuyun.model.Result;
import com.uinnova.youshuyun.service.InstrumentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author jinshuo
 * @since 2021-03-15
 */
@Service
public class InstrumentServiceImpl extends ServiceImpl<InstrumentMapper, Instrument> implements InstrumentService {

    private static final Logger logger = LoggerFactory.getLogger(InstrumentServiceImpl.class);

    @Autowired
    private InstrumentMapper instrumentMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Result<Instrument> queryListByCode(String codes) {
        List<Instrument> instruments = instrumentMapper.selectList(new LambdaQueryWrapper<Instrument>()
                .in(StringUtils.isNotBlank(codes), Instrument::getCode, Arrays.asList(codes.split(","))));

        //参数有效性校验
        if (CollectionUtils.isEmpty(instruments)) {
            return Result.error("编号无效，无法查询到正确的仪器！");
        }

        //获取需要查询的测点数据id
        List<Integer> offsetIds = instruments.stream().map(Instrument::getOffsetId).collect(Collectors.toList());
        List<Integer> temperatureId = instruments.stream().map(Instrument::getTemperatureId).collect(Collectors.toList());
        offsetIds.addAll(temperatureId);

        //组装请求参数
        String url = "http://platform.youshucloud.com/wis/api/data/curNodeData";
        JSONObject requestBody = new JSONObject();
        requestBody.put("appId", "南山水务地下暗渠三维可视化系统");
        requestBody.put("appKey", "NvjdIqnFhg8kyGnFug7ngjaUgHnajgBr");
        requestBody.put("companyId", 205070);
        requestBody.put("nodeIds", offsetIds.toArray());
        //请求第三方系统并处理回传数据
        try {
            String responseBody = restTemplate.postForEntity(url, requestBody, String.class).getBody();
            String nodesData = JSONObject.parseObject(responseBody).get("body").toString();
            JSONArray jsonArray = JSONObject.parseArray(nodesData);
            for (int i = 0; i < jsonArray.size(); i++) {
                String value = jsonArray.getJSONObject(i).get("value").toString();
                if (i >= jsonArray.size() / 2) {
                    instruments.get(i - jsonArray.size() / 2).setTemperatureValue(value);
                } else {
                    instruments.get(i).setOffsetValue(value);
                }
            }
        } catch (RestClientException e) {
            e.printStackTrace();
            return Result.error("对接第三方系统出现错误！");
        }
        return Result.list(instruments);
    }
}
